package com.example.Lezedata.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.os.Build;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.Lezedata.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.example.Lezedata.GBApplication.getContext;

public class GBUtil {
    /* 获取文件资源 */
    public static String getString(int strId) {
        return getContext().getResources().getString(strId);
    }

    /*获取版本号*/
    @RequiresApi(api = Build.VERSION_CODES.P)
    public static long packageVersion() {
        PackageManager manager = getContext().getPackageManager();
        long code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(getContext().getPackageName(), 0);
            code = info.getLongVersionCode();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }

    /*获取包名*/
    public static String packageName() {
        PackageManager manager = getContext().getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(getContext().getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return name;
    }

    /**

     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)

     */

    public static int dpTo2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**

     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp

     */

    public static int pxTo2dp(Context context,float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /// 手机号码保留前三后三
    public static String mobileReplaceToXxx(String mobile){
        CharSequence string = mobile.subSequence(3,mobile.length() - 3);
        String replace = "";
        for (int i = 0; i < string.length(); i++) {
            replace += "*";
        }
        String str = mobile.replace(string,replace);
        return str;
    }

    /*文本添加颜色*/
    public static SpannableString textAddColor(String str,int color , int start , int end){
        SpannableString spannableString = new SpannableString(str);
        ForegroundColorSpan textColor = new ForegroundColorSpan(color);
        spannableString.setSpan(textColor, start , end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    /*文本添加颜色*/
    public static SpannableString textAddColorAndFont(String str,int color ,int font , int start , int end){
        SpannableString spannableString = new SpannableString(str);
        ForegroundColorSpan textColor = new ForegroundColorSpan(color);

        StyleSpan styleSpan_B  = new StyleSpan(Typeface.BOLD);
        AbsoluteSizeSpan font2 = new AbsoluteSizeSpan(GBUtil.dpTo2px(getContext(),font));
        spannableString.setSpan(font2, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(styleSpan_B, start , end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(textColor, start , end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    /*文本添加字体*/
    public static SpannableString textAddFont(String str,int font , int start , int end){
        // 设置加粗
        StyleSpan styleSpan_B  = new StyleSpan(Typeface.BOLD);
        AbsoluteSizeSpan font2 = new AbsoluteSizeSpan(GBUtil.dpTo2px(getContext(),font));

        SpannableString spannableString = new SpannableString(str);
        spannableString.setSpan(font2, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(styleSpan_B, start , end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        return spannableString;
    }

    public static String md5(String string) throws NoSuchAlgorithmException {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getSHA256(String str){
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodestr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodestr;
    }

    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    public static String getDeviceId() {
        String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
        String serial = null;
        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            serial = "serial";
        }
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    public static boolean isDestroy(Activity mActivity) {
        if (mActivity== null || mActivity.isFinishing() || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())) {
            return true;
        } else {
            return false;
        }
    }

    public static void setHeadImage(ImageView imageView,String url){
        Object obj = imageView.getContext();
        if (obj.getClass() == Activity.class){
            if (isDestroy((Activity)obj)){
                return;
            }
        }else if (obj.getClass() == Fragment.class){
            if (isDestroy(((Fragment)obj).getActivity())){
                return;
            }
        }
        Glide.with(imageView).load(url).placeholder(R.drawable.avatar).into(imageView);
    }

    public static void setGoodsImage(ImageView imageView,String url){
        Object obj = imageView.getContext();
        if (obj.getClass() == Activity.class){
            if (isDestroy((Activity)obj)){
                return;
            }
        }else if (obj.getClass() == Fragment.class){
            if (isDestroy(((Fragment)obj).getActivity())){
                return;
            }
        }
        Glide.with(imageView).load(url).placeholder(R.drawable.icon2_240x240_y).into(imageView);
    }

    public static String RoundToString(long round){
        return String.format("Round.%s",round);
    }

    @SuppressLint("DefaultLocale")
    public static String moneyToString(long money){
        return String.format("%.2f",money/100.00f);
    }

    /// 本地文件json
    public static String getJson(String fileName, Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public static boolean stringIsEmpty(String str){
        return str == null || str.isEmpty();
    }

    public static InputFilter limitFilter(final int limit){
        InputFilter inputFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                       int dstart, int dend) {
                try {
                    //转换成中文字符集的长度
                    int destLen = dest.toString().getBytes("GB18030").length;
                    int sourceLen = source.toString().getBytes("GB18030").length;
                    Log.e("filter", String.valueOf(destLen + sourceLen));
                    if (destLen + sourceLen > limit) {
                        return "";
                    }
                    //如果按回退键
                    if (source.length() < 1 && (dend - dstart >= 1)) {
                        return dest.subSequence(dstart, dend - 1);
                    }
                    return source;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return "";
            }
        };
        return inputFilter;
    }

    public static String formatPrice(double price,boolean halfUp){
        DecimalFormat formatter = new DecimalFormat();
        // keep 2 decimal places
        formatter.setMaximumFractionDigits(2);
        formatter.setGroupingSize(3);
        formatter.setRoundingMode(halfUp ? RoundingMode.HALF_UP:RoundingMode.FLOOR);
        return formatter.format(price);
    }
    public static boolean isBee(){
        return getString(R.string.app_name).equals("Bee");
    }
    public  static String formatDateTime(long timeStmp){
        Date date = new Date(timeStmp* 1000);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);

    }
    public  static String formatDateTimeHaveHour(long timeStmp){
        Date date = new Date(timeStmp* 1000);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format.format(date);

    }
}
